package net.hserver.apm.service;


import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;
import net.hserver.apm.config.MongodbConfig;
import net.hserver.apm.util.IpUtil;
import org.bson.Document;
import org.bson.conversions.Bson;
import cn.hserver.core.ioc.annotation.Autowired;
import cn.hserver.core.ioc.annotation.Bean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Bean
public class LogInfoService {


    @Autowired
    private MongoClient mongoClient;

    public Object getPage(int page, int pageSize, String appName, String level, String chainId) {

        MongoDatabase database = mongoClient.getDatabase(MongodbConfig.DATA_BASE);
        MongoCollection<Document> requestInfo = database.getCollection("logInfo");
        Bson bson = null;

        if (appName != null && appName.trim().length() > 0) {
            bson = Filters.and(Filters.eq("appName", appName));
        }

        if (level != null && level.trim().length() > 0) {
            if (bson == null) {
                bson = Filters.and(Filters.eq("level", level));
            } else {
                bson = Filters.and(Filters.eq("level", level), bson);
            }
        }

        if (chainId != null && chainId.trim().length() > 0) {
            if (bson == null) {
                bson = Filters.and(Filters.eq("chainId", chainId));
            } else {
                bson = Filters.and(Filters.eq("chainId", chainId), bson);
            }
        }

        long count;
        MongoCursor<Document> time;
        if (bson == null) {
            count = requestInfo.countDocuments();
            time = requestInfo.find().sort(Sorts.descending("time")).skip((page - 1) * pageSize).limit(pageSize).iterator();
        } else {
            count = requestInfo.countDocuments(bson);
            time = requestInfo.find(bson).sort(Sorts.descending("time")).skip((page - 1) * pageSize).limit(pageSize).iterator();
        }
        List<Document> datas = new ArrayList<>();
        try {
            while (time.hasNext()) {
                Document next = time.next();
                datas.add(next);
            }
        } finally {
            time.close();
        }
        Map<String, Object> data = new HashMap<>();
        data.put("totalRow", count);
        data.put("list", datas);
        return data;
    }
}
